package com.uduemc.biso.node.web.service.byfeign.impl;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.entities.ThemeObject;
import com.uduemc.biso.node.core.entities.SConfig;
import com.uduemc.biso.node.core.entities.custom.CustomThemeColor;
import com.uduemc.biso.node.core.feign.SConfigFeign;
import com.uduemc.biso.node.core.utils.CustomThemeColorUtil;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.web.service.ThemeService;
import com.uduemc.biso.node.web.service.byfeign.SiteConfigService;

import cn.hutool.core.util.StrUtil;

@Service
public class SiteConfigServiceImpl implements SiteConfigService {

	@Autowired
	private SConfigFeign sConfigFeign;

	@Autowired
	private ThemeService themeServiceImpl;

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public SConfig getInfoBySiteId(long hostId, long siteId) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		RestResult restResult = sConfigFeign.findByHostSiteId(hostId, siteId);
		SConfig data = RestResultUtil.data(restResult, SConfig.class);
		return data;
	}

	@Override
	public CustomThemeColor getCustomThemeColor(SConfig sConfig) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		// 获取 sConfig中的 customThemeColorConfig 配置数据
		CustomThemeColor customThemeColorData = null;
		String customThemeColorConfig = sConfig.getCustomThemeColorConfig();
		if (StrUtil.isNotBlank(customThemeColorConfig)) {
			customThemeColorData = objectMapper.readValue(customThemeColorConfig, CustomThemeColor.class);
		}

		// 获取 ThemeObject
		String theme = sConfig.getTheme();
		ThemeObject themeObject = themeServiceImpl.getThemeObject(theme);

		CustomThemeColor makeCustomThemeColor = CustomThemeColorUtil.makeCustomThemeColor(customThemeColorData, themeObject);

		return makeCustomThemeColor;
	}

	@Override
	public void updateTemplateIdVersion(long hostId, long siteId, long templateId, String version) throws IOException {
		SConfig infoBySiteId = getInfoBySiteId(hostId, siteId);
		if (infoBySiteId == null) {
			return;
		}
		infoBySiteId.setTemplateId(templateId);
		infoBySiteId.setTemplateVersion(version);
		sConfigFeign.updateById(infoBySiteId);
	}

}
